<?php

namespace app\api\controller;

use app\admin\model\Appnotice;
use app\admin\model\Appupdate;
use app\admin\service\Aliphone;
use app\admin\service\Mail;
use app\admin\service\MailSendingTemplate;
use app\admin\service\Pay;
use app\admin\service\Upload;
use app\admin\service\QrCodeService;
use think\Db;
use think\facade\Request;
use think\Validate;
use think\helper\Time;

class Api extends Common
{
    //获取app信息
    public function getApp()
    {
        $data = [
            "appicon" => $this->app["appicon"],
            "appname" => $this->app["appname"],
            "introduction" => $this->app["introduction"],
            "author" => $this->app["author"],
            "group" => $this->app["group"],
            "view" => db("view")->where("appid", $this->app["appid"])->where("type", 0)->count(),
        ];
        return $this->successjson("查询成功", $data);
    }

    //获取当前公告
    public function getNotice()
    {
        $appid = input("appid");
        $appnotice = new Appnotice();
        $result = $appnotice->getnewnotice($appid);
        return $this->successjson("查询成功", $result);
    }

    //获取当前更新
    public function getUpdate()
    {
        $appid = input("appid");
        $appupdate = new Appupdate();
        $result = $appupdate->getnewappupdate($appid);
        return $this->successjson("查询成功", $result);
    }

    //获取公告历史记录
    public function getNoticelist()
    {
        $appid = input("appid");
        $result = db('appnotice')->where("appid", $appid)->select();
        return $this->successjson("查询成功", $result);
    }

    //获取更新历史记录
    public function getUpdatelist()
    {
        $appid = input("appid");
        $result = db('appupdate')->where("appid", $appid)->select();
        return $this->successjson("查询成功", $result);
    }

    //增加访问量
    public function addview()
    {
        $data = input();
        db("view")->insert([
            "appid" => $data["appid"],
            "time" => date("Y-m-d H:i:s", time()),
            "type" => 0
        ]);
        return $this->successjson("ok");
    }

    //获取app相关信息
    public function getview()
    {
        $appid = input("appid");
        $data["todayviewcount"] = Db::name('view')->where("appid", $appid)->where("type", 0)->whereTime('time', 'today')->count();
        $data["weekviewcount"] = Db::name('view')->where("appid", $appid)->where("type", 0)->whereTime('time', 'week')->count();
        $data["monthviewcount"] = Db::name('view')->where("appid", $appid)->where("type", 0)->whereTime('time', 'month')->count();
        $data["yearviewcount"] = Db::name('view')->where("appid", $appid)->where("type", 0)->whereTime('time', 'year')->count();
        $data["todayusercount"] = Db::name('user')->where("appid", $appid)->whereTime('create_time', 'today')->count();
        $data["weekusercount"] = Db::name('user')->where("appid", $appid)->whereTime('create_time', 'week')->count();
        $data["monthusercount"] = Db::name('user')->where("appid", $appid)->whereTime('create_time', 'month')->count();
        $data["yearusercount"] = Db::name('user')->where("appid", $appid)->whereTime('create_time', 'year')->count();
        return $this->successjson("ok", $data);
    }

    //登录
    public function Login()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'require|min:5|max:20|alphaNum',
            'password|密码' => 'require|min:5|max:20',
            'device|设备码' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$validate->check($data)) {
            return $this->errorjson($validate->getError());
        }
        //不允许登录
        if ($this->app["is_login"] == 1) {
            return $this->errorjson("此app已关闭登录入口");
        }
        $where = "username = '" . $data['username'] . "' OR phone = '" . $data['username'] . "'";
        $userinfo = db("user")->where("appid", $data["appid"])->where($where)->find();
        if ($userinfo) {
            if ($userinfo["password"] == md5($data["password"] . $userinfo["salt"])) {
                //是否禁用账号
                if ($userinfo["reasons"] == 1) {
                    return $this->errorjson($userinfo["reasons_ban"]);
                }
                //是否允许多设备登录同一账号
                if ($this->app["is_equipment"] == 1) {
                    if (!empty($userinfo["login_device"])) {
                        if ($userinfo["login_device"] != $data["device"]) {
                            return $this->errorjson("不允许新设备登录");
                        }
                    }
                }
                //异地登录是否发送短信
                // if ($this->app["is_remoteLogin"] == 0) {
                //     if ($userinfo["ip"] != "") {
                //         if (!isset($ipaddress)) {
                //             $ipaddress = Common::getaddress($userinfo["ip"]);
                //             $ipaddress = json_decode($ipaddress, true);
                //         }
                //         $newipaddress = Common::getaddress(get_real_ip());
                //         $newipaddress = json_decode($newipaddress, true);
                //         if ($ipaddress["province"] . $ipaddress["city"] != $newipaddress["province"] . $newipaddress["city"]) {
                //             $temdata = [
                //                 '{appname}' => $this->app["appname"],
                //                 '{time}' => date("Y-m-d H:i:s", time()),
                //                 '{username}' => $data["username"],
                //                 '{nickname}' => $userinfo["nickname"],
                //                 '{address}' => $newipaddress["province"] . $newipaddress["city"],
                //                 '{ip}' => $newipaddress["ip"]
                //             ];
                //             Mail::sendEmail('', $userinfo["useremail"], "", MailSendingTemplate::newdevoice($temdata), 0);
                //         }
                //     }
                // }
                // if (!isset($newipaddress)) {
                //     $newipaddress = Common::getaddress(get_real_ip());
                //     $newipaddress = json_decode($newipaddress, true);
                // }
                $usertoken = md5(getRandChar(15) . time());
                $result = [
                    "id" => $userinfo["id"],
                    "usertoken" => $usertoken,
                    "ip" => get_real_ip(),
                    "login_device" => $data["device"]
                ];
                if (empty($userinfo["register_device"])) {
                    $result["register_device"] = $data["device"];
                }
                db("user")->where("id", $userinfo["id"])->update($result);
                $result["username"] = $userinfo["username"];
                unset($result["login_device"]);
                unset($result["register_device"]);
                return $this->successjson("登录成功", $result);
            } else {
                return $this->errorjson("密码错误");
            }
        } else {
            return $this->errorjson("账号不存在");
        }
    }

    //使用手机号验证码登录
    public function phonelogin()
    {
        $data = input();
        $rule = [
            'phone|手机号' => 'require|mobile',
            'device|设备码' => 'require',
            'code|验证码' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        //不允许登录
        if ($this->app["is_login"] == 1) {
            return $this->errorjson("此app已关闭登录入口");
        }
        $code = cookie("logincode");
        $regcodetime = cookie("logincodetime");
        if (time() - $regcodetime > 300) {
            return $this->errorjson("验证码过期");
        }
        if (strtolower($code) != strtolower($data["code"])) {
            return $this->errorjson("验证码错误");
        }
        $phone = cookie("loginphone");
        $userinfo = db("user")->where("appid", $data["appid"])->where("phone", $phone)->find();
        if ($userinfo) {
            //是否禁用账号
            if ($userinfo["reasons"] == 1) {
                return $this->errorjson($userinfo["reasons_ban"]);
            }
            //是否允许多设备登录同一账号
            if ($this->app["is_equipment"] == 1) {
                if (!empty($userinfo["login_device"])) {
                    if ($userinfo["login_device"] != $data["device"]) {
                        return $this->errorjson("不允许新设备登录");
                    }
                }
            }
            //异地登录是否发送短信
            // if ($this->app["is_remoteLogin"] == 0) {
            //     if ($userinfo["ip"] != "") {
            //         if (!isset($ipaddress)) {
            //             $ipaddress = Common::getaddress($userinfo["ip"]);
            //             $ipaddress = json_decode($ipaddress, true);
            //         }
            //         $newipaddress = Common::getaddress(get_real_ip());
            //         $newipaddress = json_decode($newipaddress, true);
            //         if ($ipaddress["province"] . $ipaddress["city"] != $newipaddress["province"] . $newipaddress["city"]) {
            //             $temdata = [
            //                 '{appname}' => $this->app["appname"],
            //                 '{time}' => date("Y-m-d H:i:s", time()),
            //                 '{username}' => $data["username"],
            //                 '{nickname}' => $userinfo["nickname"],
            //                 '{address}' => $newipaddress["province"] . $newipaddress["city"],
            //                 '{ip}' => $newipaddress["ip"]
            //             ];
            //             Mail::sendEmail('', $userinfo["useremail"], "", MailSendingTemplate::newdevoice($temdata), 0);
            //         }
            //     }
            // }
            // if (!isset($newipaddress)) {
            //     $newipaddress = Common::getaddress(get_real_ip());
            //     $newipaddress = json_decode($newipaddress, true);
            // }
            $usertoken = md5(getRandChar(15) . time());
            $result = [
                "id" => $userinfo["id"],
                "usertoken" => $usertoken,
                "ip" => get_real_ip(),
                "login_device" => $data["device"]
            ];
            if (empty($userinfo["register_device"])) {
                $result["register_device"] = $data["device"];
            }
            db("user")->where("id", $userinfo["id"])->update($result);
            $result["username"] = $userinfo["username"];
            unset($result["login_device"]);
            unset($result["register_device"]);
            return $this->successjson("登录成功", $result);
        } else {
            return $this->errorjson("系统错误");
        }
    }

    //发送注册验证码
    public function logincode()
    {
        $data = input();
        $regcodetime = cookie("logincodetime");
        if ($regcodetime != "" || !empty($regcodetime)) {
            if (time() - $regcodetime < 300) {
                return $this->errorjson("5分钟内只允许发一次");
            }
        }
        if (empty($data["phone"])) {
            return $this->errorjson("请输入手机号");
        }
        $userphone = db("user")->where("appid", $data["appid"])->where("phone", $data["phone"])->find();
        if ($userphone == null) {
            return $this->errorjson("手机号未被注册");
        }
        $code = rand(100000, 999999);
        cookie("loginphone", $data["phone"], 300);
        cookie("logincode", $code, 300);
        cookie("logincodetime", time(), 300);
        $result = Aliphone::sendPhone($data["phone"], $code);
        $result = json_decode($result, true);
        if (isset($result["code"]) && $result["code"] == 200) {
            if ($result["data"]["body"]["code"] == "OK") {
                $res = 1;
            } else {
                $res = $result["data"]["body"]["message"];
            }
        } else {
            $res = $result["data"];
        }
        if ($res == 1) {
            return $this->successjson("发送成功");
        } else {
            return $this->errorjson($res);
        }
    }

    //注册
    public function Register()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'require|min:5|max:20|alphaNum',
            'password|密码' => 'require|min:5|max:20',
            'device|设备码' => 'require',
            'useremail|用户邮箱' => 'email',
            'phone|手机号' => 'mobile',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if ($this->app["is_reg"] == 1) {
            return $this->errorjson("此app已关闭注册入口");
        }
        $username = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->count();
        if ($username != 0) {
            return $this->errorjson("用户名已存在");
        }
        if ($this->app["equipment_num"] != 0) {
            $equipment_num = db("user")->where("appid", $data["appid"])->where("register_device", $data["device"])->count();
            if ($equipment_num == $this->app["equipment_num"]) {
                return $this->errorjson("该设备已达到最大注册数量");
            }
        }
        if ($this->app["is_regemailcode"] == 0) {
            if ($this->app["codetype"] == 0) {
                if (empty($data["useremail"])) {
                    return $this->errorjson("请输入邮箱");
                }
                $useremail = db("user")->where("appid", $data["appid"])->where("useremail", $data["useremail"])->count();
                if ($useremail != 0) {
                    return $this->errorjson("邮箱已存在");
                }
                $data["useremail"] == cookie("regemail");
            } else {
                if (empty($data["phone"])) {
                    return $this->errorjson("请输入手机号");
                }
                $userphone = db("user")->where("appid", $data["appid"])->where("phone", $data["phone"])->count();
                if ($userphone != 0) {
                    return $this->errorjson("手机号已被注册");
                }
                $data["phone"] == cookie("regphone");
            }
            if (!input("?code")) {
                return $this->errorjson("请输入验证码");
            }
            $code = cookie("regcode");
            $regcodetime = cookie("regcodetime");
            if ($code == "") {
                return $this->errorjson("你还没发送验证码呢");
            }
            if (time() - $regcodetime > 300) {
                return $this->errorjson("验证码过期");
            }
            if (strtolower($code) != strtolower($data["code"])) {
                return $this->errorjson("验证码错误");
            }
        }
        $data["salt"] = getRandChar(6);
        $data["password"] = md5($data["password"] . $data["salt"]);
        $data["viptime"] = time() + ($this->app["zc_vip"] * 24 * 3600);
        $data["create_time"] = date("Y-m-d H:s:i", time());
        $data["ip"] = get_real_ip();
        $data["register_device"] = $data["device"];
        $data["money"] = $this->app["zc_money"];
        $data["exp"] = $this->app["zc_exp"];
        $rs = db("user")->strict(false)->insert($data);
        if ($rs > 0) {
            return $this->successjson("注册成功");
        } else {
            return $this->errorjson("注册失败");
        }
    }

    //获取用户信息
    public function getUserInfo()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和username必须传一个");
        }
        if (input("?username")) {
            $result = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $result = db("user")->where("id", $data["id"])->where("appid", $data["appid"])->find();
        }
        if ($result == null) {
            return $this->errorjson("用户不存在");
        }
        $res = [
            "id" => $result["id"],
            "username" => $result["username"],
            "usertx" => Request::domain() . $result["usertx"],
            "userbg" => Request::domain() . $result["userbg"],
            "nickname" => $result["nickname"],
            "money" => $result["money"],
            "exp" => $result["exp"],
            "viptime" => date("Y-m-d H:i:s", $result["viptime"]),
            "sex" => $result["sex"] == 0 ? "男" : "女",
            "qq" => $result["qq"],
            "useremail" => $result["useremail"],
            "signature" => $result["signature"],
            "title" => $result["title"],
            "invitecode" => $result["invitecode"],
            "reasons" => $result["reasons"] == 0 ? "正常" : "已封禁",
            "reasons_ban" => $result["reasons_ban"],
            "create_time" => $result["create_time"],
            "ip" => $result["ip"],
            "appname" => $this->app["appname"],
            "phone" => $result["phone"],
        ];
        //等级
        $arr = $this->app["grade"];
        foreach (eval("return $arr;") as $key => $value) {
            if ($result['exp'] >= $key) {
                $res["hierarchy"] = $value;
            } else {
                break;
            }
        }
        //是否是会员
        if (time() < $result["viptime"]) {
            $res["vip"] = true;
        } else {
            $res["vip"] = false;
        }
        //签到天数
        $signinfo = db("sign")->where("userid", $result["id"])->find();
        $signlasttime = isset($signinfo["lasttime"]) ? $signinfo["lasttime"] : "";
        if ($signlasttime != "") {
            $res["signlasttime"] = date("Y-m-d H:i:s", $signlasttime);
        } else {
            $res["signlasttime"] = "";
        }
        list($starttime, $endtime) = Time::today();
        if ($signlasttime >= $starttime && $signlasttime <= $endtime) {
            $res["sign"] = true;
        } else {
            $res["sign"] = false;
        }
        $res["series_days"] = isset($signinfo["series_days"]) ? $signinfo["series_days"] : 0;
        $res["continuity_days"] = isset($signinfo["continuity_days"]) ? $signinfo["continuity_days"] : 0;
        //邀请总数
        $res["invitationcount"] = db("invitation")->where("userid", $result["id"])->count();
        //关注数量
        $res["followcount"] = db("follow")->where("userid", $result["id"])->count();
        //粉丝数量
        $res["fencount"] = db("follow")->where("followedid", $result["id"])->count();
        //帖子数量
        $res["postnum"] = db("article")->where("userid", $result["id"])->count();
        //点赞数量
        $res["likenum"] = db("view")->where("userid", $result["id"])->where("type", 2)->count();
        //评论数量
        $res["commentsnum"] = db("comments")->where("userid", $result["id"])->count();
        return $this->successjson("查询成功", $res);
    }

    //发送注册验证码
    public function sendRegcode()
    {
        $data = input();
        $regcodetime = cookie("regcodetime");
        if ($regcodetime != "" || !empty($regcodetime)) {
            if (time() - $regcodetime < 300) {
                return $this->errorjson("5分钟内只允许发一次");
            }
        }
        //判断用什么方式发短信
        if ($this->app["codetype"] == 0) {
            if (empty($data["useremail"])) {
                return $this->errorjson("请输入邮箱");
            }
            $useremail = db("user")->where("appid", $data["appid"])->where("useremail", $data["useremail"])->find();
            if ($useremail) {
                return $this->errorjson("邮箱已被注册");
            }
            $code = getRandChar(6);
            cookie("regemail", $data["useremail"], 300);
            cookie("regcode", $code, 300);
            cookie("regcodetime", time(), 300);
            $temdata = [
                '{appname}' => $this->app["appname"],
                '{useremail}' => $data["useremail"],
                '{code}' => $code,
            ];
            $res = Mail::sendEmail('', $data["useremail"], "", MailSendingTemplate::Register($temdata), 2);
        } else {
            if (empty($data["phone"])) {
                return $this->errorjson("请输入手机号");
            }
            $userphone = db("user")->where("appid", $data["appid"])->where("phone", $data["phone"])->find();
            if ($userphone) {
                return $this->errorjson("手机号已被注册");
            }
            $code = rand(100000, 999999);
            cookie("regphone", $data["phone"], 300);
            cookie("regcode", $code, 300);
            cookie("regcodetime", time(), 300);
            $result = Aliphone::sendPhone($data["phone"], $code);
            $result = json_decode($result, true);
            if (isset($result["code"]) && $result["code"] == 200) {
                if ($result["data"]["body"]["code"] == "OK") {
                    $res = 1;
                } else {
                    $res = $result["data"]["body"]["message"];
                }
            } else {
                $res = $result["data"];
            }
        }

        if ($res == 1) {
            return $this->successjson("发送成功");
        } else {
            return $this->errorjson($res);
        }
    }

    //用户签到
    public function UserSign()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和username必须传一个");
        }
        if (input("?username")) {
            $result = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $result = db("user")->where("appid", $data["appid"])->where("id", $data["id"])->find();
        }
        if ($result == null) {
            return $this->errorjson("用户不存在");
        }
        $signinfo = db("sign")->where("userid", $result["id"])->find();
        if ($signinfo) {
            list($startdaytime, $enddaytime) = Time::today();
            if ($signinfo["lasttime"] >= $startdaytime && $signinfo["lasttime"] <= $enddaytime) {
                return $this->errorjson("今天已经签到了");
            } else {
                list($yesterstartdaytime, $yesterenddaytime) = Time::yesterday();
                if ($signinfo["lasttime"] >= $yesterstartdaytime && $signinfo["lasttime"] <= $yesterenddaytime) {
                    $resdata = [
                        "continuity_days" => $signinfo["continuity_days"] + 1,
                    ];
                } else {
                    $resdata = [
                        "continuity_days" => 1,
                    ];
                }
                $resdata["lasttime"] = time();
                $resdata["series_days"] = $signinfo["continuity_days"] + 1;
                $rs = db("sign")->where("userid", $result["id"])->update($resdata);
                if ($rs > 0) {
                    if ($result["viptime"] >= time()) {
                        $userviptime = $result["viptime"];
                    } else {
                        $userviptime = time();
                    }
                    $updateuser = [
                        "money" => $result["money"] + $this->app["sign_money"],
                        "exp" => $result["exp"] + $this->app["sign_exp"],
                        "viptime" => $userviptime + $this->app["sign_vip"] * 24 * 3600,
                    ];
                    db("user")->where("id", $result["id"])->update($updateuser);
                    $this->addSysMessage(3, $result["id"]);
                    return $this->successjson("签到成功");
                } else {
                    return $this->errorjson("签到失败");
                }
            }
        } else {
            $adddata = [
                "continuity_days" => 1,
                "series_days" => 1,
                "lasttime" => time(),
                "userid" => $result["id"],
                "appid" => $data["appid"],
            ];
            $rs = db("sign")->strict(false)->insert($adddata);
            if ($rs > 0) {
                if ($result["viptime"] >= time()) {
                    $userviptime = $result["viptime"];
                } else {
                    $userviptime = time();
                }
                $updateuser = [
                    "money" => $result["money"] + $this->app["sign_money"],
                    "exp" => $result["exp"] + $this->app["sign_exp"],
                    "viptime" => $userviptime + $this->app["sign_vip"] * 24 * 3600,
                ];
                db("user")->where("id", $result["id"])->update($updateuser);
                $this->addSysMessage(3, $result["id"]);
                return $this->successjson("签到成功");
            } else {
                return $this->errorjson("签到失败");
            }
        }
    }

    //发送找回密码验证码
    public function GetPasswordCode()
    {
        $data = input();
        if (empty($data["username"])) {
            return $this->errorjson("请输入用户名");
        }
        $username = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        if ($username) {
            if ($username["useremail"] == "") {
                return $this->errorjson("该账号未绑定任何邮箱");
            }
            $passcodetime = cookie("passcodetime");
            if ($passcodetime != "" || !empty($passcodetime)) {
                if (time() - $passcodetime < 300) {
                    return $this->errorjson("5分钟内只允许发一次");
                }
            }
            $code = getRandChar(6);
            cookie("passcode", $code, 300);
            cookie("passcodetime", time(), 300);
            $temdata = [
                '{appname}' => $this->app["appname"],
                '{username}' => $username["username"],
                '{code}' => $code,
            ];
            $res = Mail::sendEmail('', $username["useremail"], "", MailSendingTemplate::findPassword($temdata), 2);
            if ($res == 1) {
                return $this->successjson("邮件发送成功");
            } else {
                return $this->errorjson($res);
            }
        } else {
            return $this->errorjson("该账号未被注册");
        }
    }

    //找回密码
    public function GetPassword()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'require|min:5|max:20|alphaNum',
            'password|新密码' => 'require|min:5|max:20',
            'code|验证码' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $userinfo = db("user")->where("username", $data["username"])->where('appid', $data["appid"])->find();
        if ($userinfo == null) {
            return $this->errorjson("账号不存在");
        }
        if (!input("?code")) {
            return $this->errorjson("请输入验证码");
        }
        $code = cookie("passcode");
        $passcodetime = cookie("passcodetime");
        if ($code == "") {
            return $this->errorjson("你还没发送验证码呢");
        }
        if (time() - $passcodetime > 300) {
            return $this->errorjson("验证码过期");
        }
        if (strtolower($code) != strtolower($data["code"])) {
            return $this->errorjson("验证码错误");
        }
        $update = [
            "password" => md5($data["password"] . $userinfo["salt"]),
        ];
        $rs = db('user')->where('id', $userinfo["id"])->update($update);
        return $this->successjson("修改成功");
    }

    //修改用户信息
    public function updateuserInfo()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'require|min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'id|用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $updatedata = [];
        if (input("?nickname")) {
            $updatedata["nickname"] = $data["nickname"];
        }
        if (input("?qq")) {
            $updatedata["qq"] = $data["qq"];
        }
        if (input("?useremail")) {
            $updatedata["useremail"] = $data["useremail"];
        }
        if (input("?signature")) {
            $updatedata["signature"] = $data["signature"];
        }
        if (input("?sex")) {
            if ($data["sex"] == "男" || $data["sex"] == 1) {
                $updatedata["sex"] = 0;
            } else {
                $updatedata["sex"] = 1;
            }
        }
        if (input("?useremail")) {
            if ($userinfo["useremail"] != $data["useremail"]) {
                $updatedata["useremail"] = $data["useremail"];
                $emailuserinfo = db("user")->where("appid", $data["appid"])->where("useremail", $data["useremail"])->find();
                if ($emailuserinfo != null) {
                    return $this->errorjson("邮箱已存在");
                }
            }
        }
        if (input("?phone")) {
            if ($userinfo["phone"] != $data["phone"]) {
                $updatedata["phone"] = $data["phone"];
                $phoneuserinfo = db("user")->where("appid", $data["appid"])->where("phone", $data["phone"])->find();
                if ($phoneuserinfo != null) {
                    return $this->errorjson("手机号已存在");
                }
            }
        }

        db("user")->where("id", $userinfo["id"])->update($updatedata);
        return $this->successjson("修改成功");
    }

    //头像上传
    public function UploadHead()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'require|min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'id|用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $upload = new Upload();
        $result = $upload->upload('file', 1);
        $result = json_decode($result, true);
        if ($result["code"] == 200) {
            $usertx = $result["data"]["filePath"];
            db("user")->where("id", $userinfo["id"])->update(["usertx" => $usertx]);
            return $this->successjson($result["data"]["fullPath"]);
        } else {
            return $this->errorjson("上传失败");
        }
    }

    //背景上传
    public function UploadBg()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'require|min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'id|用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $upload = new Upload();
        $result = $upload->upload('file', 1);
        $result = json_decode($result, true);
        if ($result["code"] == 200) {
            $userbg = $result["data"]["filePath"];
            db("user")->where("id", $userinfo["id"])->update(["userbg" => $userbg]);
            return $this->successjson($result["data"]["fullPath"]);
        } else {
            return $this->errorjson("上传失败");
        }
    }

    //1金币排行榜2经验
    public function UserList()
    {
        $data = input();
        $sort = input('?sort') ? input('sort') : 'money';
        $sortOrder = input('?sortOrder') ? input('sortOrder') : 'desc';
        if ($sort != "money" && $sort != "exp") {
            return $this->errorjson("sort参数错误");
        }
        if ($sortOrder != "desc" && $sortOrder != "asc") {
            return $this->errorjson("sortOrder参数错误");
        }
        if ($sort == "money") {
            $need_field = ['id', 'username', 'nickname', 'usertx', 'money', 'title'];
        } else {
            $need_field = ['id', 'username', 'nickname', 'usertx', 'exp', 'title'];
        }
        $res = db('user')->where('appid', $data["appid"])->order($sort, $sortOrder)->field($need_field)->limit($this->limit)->select();
        foreach ($res as $key => $value) {
            $res[$key]["usertx"] = Request::domain() . $value["usertx"];
        }
        return $this->successjson("查询成功", $res);
    }

    //修改密码
    public function UpdatePassword()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'oldpwd|老密码' => 'require',
            'newpwd|新密码' => 'require',
            'id' => 'number'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        if ($userinfo['password'] != md5($data['oldpwd'] . $userinfo["salt"])) {
            return $this->errorjson("旧密码错误");
        }
        if ($userinfo['password'] == md5($data['newpwd'] . $userinfo["salt"])) {
            return $this->successjson("修改成功");
        }
        db('user')->where("id", $userinfo["id"])->update(['password' => md5($data['newpwd'] . $userinfo["salt"])]);
        return $this->successjson("修改成功");
    }

    //生成邀请码
    public function Getinvitecode()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'id' => 'number'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        if ($userinfo['invitecode'] == "" || $userinfo['invitecode'] == null) {
            $invitecode = getRandChar(strlen($data['username'])) . $userinfo["id"];
            db('user')->where('id', $userinfo['id'])->update(['invitecode' => $invitecode]);
            return $this->successjson("生成成功", $invitecode);
        } else {
            return $this->errorjson("已经生成过邀请码");
        }
    }

    //填写邀请码
    public function Invitation()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken|用户token' => 'require',
            'id' => 'number',
            'invitecode' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($data["usertoken"] != $userinfo["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $rs = db("invitation")->where("newuserid", $userinfo["id"])->find();
        if ($rs) {
            return $this->errorjson("已经填写过邀请码了");
        }
        $inviteuserinfo = db("user")->where("appid", $data["appid"])->where("invitecode", $data["invitecode"])->find();
        if ($inviteuserinfo == null) {
            return $this->errorjson("邀请码不存在");
        }
        if ($inviteuserinfo["viptime"] >= time()) {
            $userviptime = $inviteuserinfo["viptime"];
        } else {
            $userviptime = time();
        }
        $updateinvitecode = [
            "money" => $inviteuserinfo["money"] + $this->app["invitation_money"],
            "exp" => $inviteuserinfo["exp"] + $this->app["invitation_exp"],
            "viptime" => $userviptime + $this->app["invitation_vip"] * 24 * 3600,
        ];
        db("user")->where("id", $inviteuserinfo["id"])->update($updateinvitecode);
        $adddata = [
            "userid" => $inviteuserinfo["id"],
            "newuserid" => $userinfo["id"],
            "appid" => $data["appid"],
            "createtime" => date("Y-m-d H:i:s", time()),
        ];
        db("invitation")->insert($adddata);
        return $this->successjson("填写完成");
    }

    //邀请排行榜
    public function GetinviterList()
    {
        $sortOrder = input('?sortOrder') ? input('sortOrder') : 'desc';
        if ($sortOrder != "desc" && $sortOrder != "asc") {
            return $this->errorjson("sortOrder参数错误");
        }
        $result = db('invitation')
            ->alias("i")
            ->join('user u', "i.userid = u.id")
            ->group("i.userid")
            ->field("i.userid as id,count(i.id) as count,u.username,u.nickname,u.usertx,u.title")
            ->order("count", $sortOrder)
            ->limit($this->limit)
            ->select();
        foreach ($result as $key => $value) {
            $result[$key]["usertx"] = Request::domain() . $value["usertx"];
        }
        return $this->successjson("查询成功", $result);
    }

    //使用卡密
    public function UserKm()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'id|用户id' => 'number',
            'km|卡密' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $kminfo = db("km")->where("appid", $data["appid"])->where("km", $data["km"])->where("type", 0)->find();
        if ($kminfo == null) {
            return $this->errorjson("卡密不存在");
        }
        if ($kminfo["state"] == 1) {
            return $this->errorjson("卡密已被使用");
        }
        if ($userinfo["viptime"] >= time()) {
            $userviptime = $userinfo["viptime"];
        } else {
            $userviptime = time();
        }
        $updateuser = [
            "money" => $userinfo["money"] + $kminfo["money"],
            "exp" => $userinfo["exp"] + $kminfo["exp"],
            "viptime" => $userviptime + $kminfo["viptime"] * 24 * 3600,
        ];
        db("user")->where("id", $userinfo["id"])->update($updateuser);
        $updatekm = [
            "state" => 1,
            "username" => $userinfo["username"],
            "usetime" => date("Y-m-d H:i:s", time()),
        ];
        db("km")->where("id", $kminfo["id"])->update($updatekm);
        $this->addSysMessage(5, $userinfo["id"], $kminfo["id"]);
        return $this->successjson("使用成功");
    }

    //使用登录卡密
    public function UserLoginkm()
    {
        $data = input();
        $rule = [
            'device|设备码' => 'require',
            'km|卡密' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $kminfo = db("km")->where("appid", $data["appid"])->where("km", $data["km"])->where("type", 1)->find();
        if ($kminfo == null) {
            return $this->errorjson("卡密不存在");
        }
        if ($kminfo["state"] == 1) {
            //结束时间
            $endtime = strtotime($kminfo["usetime"]) + $kminfo["expire"] * 24 * 3600;
            if ($kminfo["device"] == $data["device"]) {
                if ($endtime > time()) {
                    $result = [
                        "expire" => date("Y-m-d H:i:s", $endtime),
                    ];
                    return $this->successjson("登录成功", $result);
                } else {
                    return $this->errorjson("卡密已过期");
                }
            } else {
                return $this->errorjson("卡密已被使用");
            }
        } else {
            $updatekm = [
                "state" => 1,
                "device" => $data["device"],
                "usetime" => date("Y-m-d H:i:s", time()),
            ];
            $endtime = time() + $kminfo["expire"] * 24 * 3600;
            $result = [
                "expire" => date("Y-m-d H:i:s", $endtime),
            ];
            db("km")->where("id", $kminfo["id"])->update($updatekm);
            return $this->successjson("登录成功", $result);
        }
    }

    //获取商品列表
    public function GetShopList()
    {
        $data = input();
        $result = db("shop")
            ->where("appid", $data["appid"])
            ->field('content', true)
            ->page($this->page)
            ->limit($this->limit)
            ->select();
        foreach ($result as $key => $value) {
            $result[$key]["subimages"] = Request::domain() . $value["subimages"];
        }
        return $this->successjson("查询成功", $result);
    }

    //获取商品信息
    public function GetShopInfo()
    {
        $id = input("id");
        if (!input("?id")) {
            return $this->errorjson("商品不存在");
        }
        $result = db("shop")->where("id", $id)->field("content", true)->find();
        $result["subimages"] = Request::domain() . $result["subimages"];
        return $this->successjson("查询成功", $result);
    }

    //购买商品
    public function BuyShop()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'id|用户id' => 'number',
            'usertoken' => 'require',
            'shopid|商品id' => 'require|number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $shopinfo = db("shop")->where("id", $data["shopid"])->find();
        if ($shopinfo == null) {
            return $this->errorjson("商品不存在");
        }
        if ($shopinfo["stock"] == 0) {
            return $this->errorjson("库存不足");
        }
        //判断支付方式类型
        if ($shopinfo["payment"] == 0) {
            //支付宝支付
            $payment = Pay::createPaymentInstance($shopinfo["payment"]);
            $orderdata = [
                "out_trade_no" => getorderNumber("mr", $userinfo["id"]),
                "total_amount" => $shopinfo["price"],
                "subject" => $shopinfo["name"] . "(" . $shopinfo["detail"] . ")",
            ];
            $sentData = $payment->createPaymentOrder(Pay::getPaymentById($shopinfo["payment"]), $orderdata);
            $sentData = json_decode($sentData, true);
            if (isset($sentData["alipay_trade_precreate_response"]["code"]) && $sentData["alipay_trade_precreate_response"]["code"] == 10000) {
                QrCodeService::lineQrCode($sentData["alipay_trade_precreate_response"]["qr_code"], $orderdata["out_trade_no"]);
                $addshoporder = [
                    "order_no" => $orderdata["out_trade_no"],
                    "shop_id" => $data["shopid"],
                    "userid" => $userinfo["id"],
                    "status" => 0,
                    "createtime" => date("Y-m-d H:i:s", time()),
                    "appid" => $data["appid"],
                    "price" => $shopinfo["price"],
                ];
                db("order")->insert($addshoporder);
                return $this->successjson("提交成功", [
                    "money" => $shopinfo["price"],
                    "out_trade_no" => $orderdata["out_trade_no"],
                    "paycode" => Request::domain() . "/uploads/pay/" . $orderdata["out_trade_no"] . ".png",
                    "h5_qrurl" => "alipays://platformapi/startapp?appId=60000105&url=" . $sentData["alipay_trade_precreate_response"]["qr_code"]
                ]);
            } else {
                return $this->errorjson("购买失败");
            }
        } elseif ($shopinfo["payment"] == 1) {
            //金币支付
            if ($userinfo["money"] < $shopinfo["price"]) {
                return $this->errorjson("金币不足");
            }
            //订单记录
            $addshoporder = [
                "order_no" => getorderNumber("mr", $userinfo["id"]),
                "shop_id" => $data["shopid"],
                "userid" => $userinfo["id"],
                "status" => 1,
                "paymenttime" => date("Y-m-d H:i:s", time()),
                "createtime" => date("Y-m-d H:i:s", time()),
                "appid" => $data["appid"],
                "price" => $shopinfo["price"],
            ];
            db("order")->insert($addshoporder);
            db("shop")->where("id", $data["shopid"])->update([
                "stock" => $shopinfo["stock"] - 1,
            ]);
            if ($shopinfo["type"] == 0) {
                //兑换会员
                //增加用户会员时长
                if ($userinfo["viptime"] < time()) {
                    $viptime = time() + 3600 * 24 * $shopinfo["content"];
                } else {
                    $viptime = $userinfo["viptime"] + 3600 * 24 * $shopinfo["content"];
                }
                db("user")->where("id", $userinfo["id"])->update([
                    "viptime" => $viptime,
                    "money" => $userinfo["money"] - $shopinfo["price"]
                ]);
                $this->addSysMessage(4, $userinfo["id"], $shopinfo["id"]);
                return $this->successjson("购买成功");
            } else {
                db("user")->where("id", $userinfo["id"])->update([
                    "money" => $userinfo["money"] - $shopinfo["price"]
                ]);
                $this->addSysMessage(4, $userinfo["id"], $shopinfo["id"]);
                return $this->successjson("购买成功", $shopinfo["content"]);
            }
            $this->addSysMessage(4, $userinfo["id"], $shopinfo["id"]);
        } elseif ($shopinfo["payment"] == 2) {
            //积分支付
            if ($userinfo["exp"] < $shopinfo["price"]) {
                return $this->errorjson("积分不足");
            }
            //订单记录
            $addshoporder = [
                "order_no" => getorderNumber("mr", $userinfo["id"]),
                "shop_id" => $data["shopid"],
                "userid" => $userinfo["id"],
                "status" => 1,
                "paymenttime" => date("Y-m-d H:i:s", time()),
                "createtime" => date("Y-m-d H:i:s", time()),
                "appid" => $data["appid"],
                "price" => $shopinfo["price"],
            ];
            db("order")->insert($addshoporder);
            db("shop")->where("id", $data["shopid"])->update([
                "stock" => $shopinfo["stock"] - 1,
            ]);
            if ($shopinfo["type"] == 0) {
                //兑换会员
                //增加用户会员时长
                if ($userinfo["viptime"] < time()) {
                    $viptime = time() + 3600 * 24 * $shopinfo["content"];
                } else {
                    $viptime = $userinfo["viptime"] + 3600 * 24 * $shopinfo["content"];
                }
                db("user")->where("id", $userinfo["id"])->update([
                    "viptime" => $viptime,
                    "exp" => $userinfo["exp"] - $shopinfo["price"]
                ]);
                $this->addSysMessage(4, $userinfo["id"], $shopinfo["id"]);
                return $this->successjson("购买成功");
            } else {
                db("user")->where("id", $userinfo["id"])->update([
                    "exp" => $userinfo["exp"] - $shopinfo["price"]
                ]);
                $this->addSysMessage(4, $userinfo["id"], $shopinfo["id"]);
                return $this->successjson("购买成功", $shopinfo["content"]);
            }
        } elseif ($shopinfo["payment"] == 3) {
            //获取源支付的支付方式
            $pay_type = input("?paytype") ? input("paytype") : "alipay";
            if ($pay_type != "alipay" && $pay_type != "qqpay" && $pay_type != "wxpay") {
                return $this->errorjson("源支付的支付方式错误");
            }
            //源支付的方式
            $payment = Pay::createPaymentInstance($shopinfo["payment"]);
            $orderdata = [
                "out_trade_no" => getorderNumber("mr", $userinfo["id"]),
                "money" => $shopinfo["price"],
                "name" => $shopinfo["name"] . "(" . $shopinfo["detail"] . ")",
                "type" => $pay_type,
            ];
            $sentData = $payment->createPaymentOrder(Pay::getPaymentById($shopinfo["payment"]), $orderdata);
            if ($sentData != 1) {
                $sentData = json_decode($sentData, true);
                if ($pay_type == "qqpay") {
                    //qq支付的时候 对url解码
                    $sentData["qrcode"] = urldecode($sentData["qrcode"]);
                }
                QrCodeService::lineQrCode($sentData["qrcode"], $orderdata["out_trade_no"]);
                $addshoporder = [
                    "order_no" => $orderdata["out_trade_no"],
                    "shop_id" => $data["shopid"],
                    "userid" => $userinfo["id"],
                    "status" => 0,
                    "createtime" => date("Y-m-d H:i:s", time()),
                    "appid" => $data["appid"],
                    "price" => $shopinfo["price"],
                ];
                db("order")->insert($addshoporder);
                return $this->successjson("提交成功", [
                    "money" => $shopinfo["price"],
                    "out_trade_no" => $sentData["out_trade_no"],
                    "paycode" => Request::domain() . "/uploads/pay/" . $orderdata["out_trade_no"] . ".png",
                    "h5_qrurl" => $sentData["h5_qrurl"],
                ]);
            } else {
                return $this->errorjson("购买失败");
            }
        } elseif ($shopinfo["payment"] == 4) {
            //获取易支付的支付方式
            $pay_type = input("?paytype") ? input("paytype") : "alipay";
            $result_type = input("?resulttype") ? input("resulttype") : "submit";
            if ($pay_type != "alipay" && $pay_type != "qqpay" && $pay_type != "wxpay") {
                return $this->errorjson("易支付的支付方式错误");
            }
            if ($result_type != "submit" && $result_type != "qrcode" && $result_type != "mapi") {
                return $this->errorjson("易支付的发起支付方式错误");
            }
            //易支付的方式
            $payment = Pay::createPaymentInstance($shopinfo["payment"]);
            $orderdata = [
                "out_trade_no" => getorderNumber("mr", $userinfo["id"]),
                "money" => $shopinfo["price"],
                "name" => $shopinfo["name"] . "(" . $shopinfo["detail"] . ")",
                "type" => $pay_type,
            ];
            $sentData = $payment->createPaymentOrder(Pay::getPaymentById($shopinfo["payment"]), $orderdata, $result_type);
            if ($sentData == null) {
                return $this->errorjson("易支付配置错误");
            }
            if ($sentData["code"] == 1) {
                $paycode = "";
                $urlscheme = "";
                $payurl = "";
                if ($result_type == 'mapi') {
                    if (isset($sentData["payurl"])) {
                        $payurl = $sentData["payurl"];
                    }
                    if (isset($sentData["qrcode"])) {
                        QrCodeService::lineQrCode($sentData["qrcode"], $orderdata["out_trade_no"]);
                        $paycode = Request::domain() . "/uploads/pay/" . $orderdata["out_trade_no"] . ".png";
                    }
                    if (isset($sentData["urlscheme"])) {
                        $urlscheme = $sentData["urlscheme"];
                    }
                }
                if ($result_type == 'qrcode') {
                    QrCodeService::lineQrCode($sentData["qrcode"], $orderdata["out_trade_no"]);
                    $paycode = Request::domain() . "/uploads/pay/" . $orderdata["out_trade_no"] . ".png";
                }
                if ($result_type == 'submit') {
                    $payurl = $sentData["payurl"];
                }
                $addshoporder = [
                    "order_no" => $orderdata["out_trade_no"],
                    "shop_id" => $data["shopid"],
                    "userid" => $userinfo["id"],
                    "status" => 0,
                    "createtime" => date("Y-m-d H:i:s", time()),
                    "appid" => $data["appid"],
                    "price" => $shopinfo["price"],
                ];
                db("order")->insert($addshoporder);
                return $this->successjson("提交成功", [
                    "money" => $shopinfo["price"],
                    "out_trade_no" => $orderdata["out_trade_no"],
                    "paycode" => $paycode,
                    "urlscheme" => $urlscheme,
                    "payurl" => $payurl,
                ]);
            } else {
                return $this->errorjson($sentData["msg"]);
            }
        } else {
            return $this->errorjson("服务器错误");
        }
    }

    //订单记录
    public function Getshoporder()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'id|用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $result = db('order')->alias('o')
            ->join("shop s", "s.id = o.shop_id")
            ->join("user u", "u.id = o.userid")
            ->where("userid", $userinfo["id"])
            ->field("o.*,u.username,s.price,s.name,s.subimages,s.detail,s.payment,s.type,s.content")
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        foreach ($result as $key => $value) {
            $result[$key]["subimages"] = Request::domain() . $value["subimages"];
        }
        return $this->successjson("查询成功", $result);
    }

    //查询订单的状态
    public function Getorderstatus()
    {
        $data = input();
        $rule = [
            'order_no|订单号' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $orderinfo = db("order")->where("order_no", $data["order_no"])->where("appid", $data["appid"])->find();
        if ($orderinfo != null) {
            if ($orderinfo["status"] ==  1) {
                return $this->successjson(true);
            } else {
                return $this->successjson(false);
            }
        } else {
            return $this->errorjson("不存在此订单");
        }
    }

    //获取版块列表
    public function listSection()
    {
        $data = input();
        $result = db('plate')
            ->where("appid", $data["appid"])
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        foreach ($result as $key => $value) {
            $result[$key]["plateicon"] = Request::domain() . $value["plateicon"];
            $result[$key]["postnum"] = db("article")->where("plateid", $value["id"])->count();
        }
        return $this->successjson("查询成功", $result);
    }

    //获取板块信息
    public function getSection()
    {
        $data = input();
        $rule = [
            'id|板块id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $result = db("plate")->where("id", $data["id"])->find();
        if ($result == null) {
            return $this->errorjson("板块不存在");
        }
        $result["plateicon"] = Request::domain() . $result["plateicon"];
        $result["postnum"] = db("article")->where("plateid", $result["id"])->count(); //帖子总量
        //循环获取版主
        $admin = explode(",", $result["admin"]);
        $admininfo = [];
        foreach ($admin as $key => $value) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $value)->find();
            if ($userinfo == null) {
                continue;
            }
            $admininfo[$key]["id"] = $userinfo["id"];
            $admininfo[$key]["username"] = $userinfo["username"];
            $admininfo[$key]["nickname"] = $userinfo["nickname"];
            $admininfo[$key]["usertx"] = Request::domain() . $userinfo["usertx"];
        }
        $result["admininfo"] = $admininfo;
        return $this->successjson("ok", $result);
    }

    //获取帖子列表
    public function listPost()
    {
        $data = input();
        $where = "a.appid={$data['appid']} ";
        //用户id
        if (input("?userid") || input("?username")) {
            if (input("?username")) {
                $userwhere = " and u.username = '" . $data['username'] . "'";
            }
            if (input("?userid")) {
                $userwhere = " and a.userid = {$data['userid']}";
            }
            $where .= $userwhere;
        }
        //板块id
        if (input("?plateid")) {
            $where .= " and a.plateid = {$data['plateid']}";
        }
        //是否置顶
        if (input("?top")) {
            $where .= " and a.top = {$data['top']}";
        }
        //是否热门
        if (input("?popular")) {
            $where .= " and a.popular = {$data['popular']}";
        }
        //状态
        if (input("?status")) {
            $where .= " and a.status = {$data['status']}";
        }
        //帖子类型
        if (input("?is_type")) {
            $where .= " and a.is_type = {$data['is_type']}";
        }
        //模糊搜索
        if (input("?keyword")) {
            $where .= " and a.title like '%" . $data["keyword"] . "%' or a.content like '%" . $data["keyword"] . "%'";
        }
        $sort = input("?sort") ? $data["sort"] : "createtime";
        $sortOrder = input("?sortOrder") ? $data["sortOrder"] : 'desc';
        if ($sort != "createtime" && $sort != "updatetime") {
            return $this->errorjson("sort参数错误");
        }
        if ($sortOrder != "desc" && $sortOrder != "asc") {
            return $this->errorjson("sortOrder参数错误");
        }
        $result = db("article")
            ->alias("a")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("a.*,u.username,u.nickname,u.usertx,u.title as usertitle,p.platename")
            ->where($where)
            ->order("a." . $sort, $sortOrder)
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        $postcount = db("article")
            ->alias("a")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("a.*,u.username,u.nickname,u.usertx,p.platename")
            ->where($where)
            ->count();
        $pagecount = ceil($postcount / $this->limit);
        foreach ($result as $key => $value) {
            if ($value["video_cover"] != "") {
                $result[$key]["video_cover"] = Request::domain() . $value["video_cover"];
            }
            $result[$key]["usertx"] = Request::domain() . $value["usertx"];
            //本地图片
            $pic = explode(",", $value["pic_url"]);
            $pic_url_array = [];
            foreach ($pic as $k => $v) {
                if ($v == "") continue;
                array_push($pic_url_array, Request::domain() . $v);
            }
            $pic_url = implode(",", $pic_url_array);
            //网络图片
            $network_pictures_start = explode(",", $value["network_pictures"]);
            $network_pictures_array = [];
            foreach ($network_pictures_start as $k1 => $v1) {
                if ($v1 == "") continue;
                array_push($network_pictures_array, $v1);
            }
            $network_pictures = implode(",", $network_pictures_array);
            if ($value["pic_url"] != "") {
                if ($value["network_pictures"] != "") {
                    $result[$key]["pic_url"] = $pic_url . "," . $network_pictures;
                } else {
                    $result[$key]["pic_url"] = $pic_url;
                }
            } else {
                if ($value["network_pictures"] != "") {
                    $result[$key]["pic_url"] = $network_pictures;
                } else {
                    $result[$key]["pic_url"] = "";
                }
            }
            unset($result[$key]["network_pictures"]);
            $result[$key]["view"] = db("view")->where("postid", $value["id"])->where("type", 1)->count();
            $result[$key]["thumbs"] = db("view")->where("postid", $value["id"])->where("type", 2)->count();
            //评论量
            $result[$key]["comment"] = db("comments")->where("postid", $value["id"])->count();
        }
        return $this->successjson($pagecount, $result);
    }

    //获取帖子信息
    public function getPost()
    {
        $data = input();
        $rule = [
            'id|帖子id' => 'require|number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        $postinfo = db("article")
            ->alias("a")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("a.*,u.username,u.nickname,u.usertx,u.title as usertitle,p.platename")
            ->where("a.id", $data["id"])
            ->find();
        if ($postinfo == null) {
            return $this->errorjson("帖子不存在");
        }
        //增加帖子访问量
        $adddata = [
            "appid" => $data["appid"],
            "time" => date("Y-m-d H:i:s", time()),
            "type" => 1,
            "userid" => isset($userinfo) ? $userinfo["id"] : 0,
            "postid" => $data["id"]
        ];
        db("view")->insert($adddata);
        //组装帖子信息
        if ($postinfo["video_cover"] != "") {
            $postinfo["video_cover"] = Request::domain() . $postinfo["video_cover"];
        }
        $postinfo["usertx"] = Request::domain() . $postinfo["usertx"];
        //本地图片
        $pic = explode(",", $postinfo["pic_url"]);
        $pic_url_array = [];
        foreach ($pic as $k => $v) {
            if ($v == "") continue;
            array_push($pic_url_array, Request::domain() . $v);
        }
        $pic_url = implode(",", $pic_url_array);
        //网络图片
        $network_pictures_start = explode(",", $postinfo["network_pictures"]);
        $network_pictures_array = [];
        foreach ($network_pictures_start as $k1 => $v1) {
            if ($v1 == "") continue;
            array_push($network_pictures_array, $v1);
        }
        $network_pictures = implode(",", $network_pictures_array);
        if ($postinfo["pic_url"] != "") {
            if ($postinfo["network_pictures"] != "") {
                $postinfo["pic_url"] = $pic_url . "," . $network_pictures;
            } else {
                $postinfo["pic_url"] = $pic_url;
            }
        } else {
            if ($postinfo["network_pictures"] != "") {
                $postinfo["pic_url"] = $network_pictures;
            } else {
                $postinfo["pic_url"] = "";
            }
        }
        //帖子访问量
        $postinfo["view"] = db("view")->where("postid", $data["id"])->where("type", 1)->count();
        //点赞量
        $postinfo["thumbs"] = db("view")->where("postid", $data["id"])->where("type", 2)->count();
        //评论量
        $postinfo["comment"] = db("comments")->where("postid", $data["id"])->count();
        //获取用户是否点赞了帖子 0未点赞 1点赞
        if (isset($userinfo)) {
            $is_thumbs = db("view")->where("postid", $data["id"])->where("userid", $userinfo["id"])->where("type", 2)->find();
            if ($is_thumbs == null) {
                $postinfo["is_thumbs"] = 0;
            } else {
                $postinfo["is_thumbs"] = 1;
            }
        } else {
            $postinfo["is_thumbs"] = 0;
        }
        //查询关注状态
        if (isset($userinfo)) {
            $followinfo = db("follow")->where("userid", $userinfo["id"])->where("followedid", $postinfo["userid"])->find();
            $ffollowinfo = db("follow")->where("userid", $postinfo["userid"])->where("followedid", $userinfo["id"])->find();
            if ($followinfo != null) {
                if ($ffollowinfo != null) {
                    $postinfo["followstate"] = 0;   //互相关注
                } else {
                    $postinfo["followstate"] = 2;  //我关注了他
                }
            } else {
                if ($ffollowinfo != null) {
                    $postinfo["followstate"] = 1;   //他关注了我
                } else {
                    $postinfo["followstate"] = 3;  //互相都没有关注
                }
            }
        } else {
            $postinfo["followstate"] = 3;
        }
        unset($postinfo["network_pictures"]);
        //分享链接
        $postinfo["posturl"] = Request::domain() . "/post/" . $postinfo["id"] . ".html";
        return $this->successjson("ok", $postinfo);
    }

    //新增帖子
    public function post()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'id|用户id' => 'number',
            'usertoken' => 'require',
            'title|标题' => 'require',
            'content|内容' => 'require',
            'plateid|板块id' => 'require|number',
            'type|帖子类型' => 'number'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?id")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?id")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["id"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $plateinfo = db("plate")->where("id", $data["plateid"])->where("appid", $data["appid"])->find();
        if ($plateinfo == null) {
            return $this->errorjson("板块不存在");
        }
        $plateadmin = explode(",", $plateinfo["admin"]);
        if ($plateinfo["satus"] == 0) {
            if (!inarraybyId($plateadmin, $userinfo["id"])) {
                return $this->errorjson("本版块只限管理员发布");
            }
        }
        $expand = input("?expand") ? $data["expand"] : "";
        $network_pictures = input("?network_pictures") ? $data["network_pictures"] : "";
        $is_type = input("?type") ? $data["type"] : 0;
        $pic_url = [];
        $video_url = [];
        $video_cover = [];
        $attachment = [];

        if (!empty($_FILES) && !empty($_FILES["file"])) {
            $upload = new Upload();
            $result = $upload->upload('file', 1);
            $result = json_decode($result, true);
            if ($result["code"] == 400) {
                return $this->errorjson("文件上传失败");
            }
            foreach ($result["data"] as $key => $value) {
                array_push($pic_url, $value["filePath"]);
                array_push($video_url, $value["filePath"]);
            }
        }
        if (!empty($_FILES) && !empty($_FILES["video_cover"])) {
            $upload = new Upload();
            $result_cover = $upload->upload('video_cover', 1);
            $result_cover = json_decode($result_cover, true);
            if ($result_cover["code"] == 400) {
                return $this->errorjson("文件上传失败");
            }
            foreach ($result_cover["data"] as $key => $value) {
                array_push($video_cover, $value["filePath"]);
            }
        }
        if (!empty($_FILES) && !empty($_FILES["attachment"])) {
            $upload = new Upload();
            $result_attachment = $upload->upload('attachment', 1);
            $result_attachment = json_decode($result_attachment, true);
            if ($result_attachment["code"] == 400) {
                return $this->errorjson("文件上传失败");
            }
            foreach ($result_attachment["data"] as $key => $value) {
                array_push($attachment, $value["filePath"]);
            }
        }
        $poststate = $this->app["poststate"] == 0 ? 0 : 1;
        $pic_url = implode(",", $pic_url);
        $video_url = implode(",", $video_url);
        $video_cover = implode(",", $video_cover);
        $attachment = implode(",", $attachment);
        if ($is_type == 0) {
            $adddata = [
                "title" => $data["title"],
                "content" => $data["content"],
                "pic_url" => $pic_url,
                "is_type" => 0,
                "userid" => $userinfo["id"],
                "appid" => $data["appid"],
                "plateid" => $plateinfo["id"],
                "createtime" => date("Y-m-d H:i:s", time()),
                "updatetime" => date("Y-m-d H:i:s", time()),
                "ip" => get_real_ip(),
                "status" => $poststate,
                "network_pictures" => $network_pictures,
                "expand" => $expand,
                "attachment" => $attachment,
            ];
        } else {
            $adddata = [
                "title" => $data["title"],
                "content" => $data["content"],
                "video_url" => $video_url,
                "video_cover" => $video_cover,
                "is_type" => 1,
                "userid" => $userinfo["id"],
                "appid" => $data["appid"],
                "plateid" => $plateinfo["id"],
                "createtime" => date("Y-m-d H:i:s", time()),
                "updatetime" => date("Y-m-d H:i:s", time()),
                "ip" => get_real_ip(),
                "status" => $poststate,
                "expand" => $expand,
                "attachment" => $attachment,
            ];
        }
        db("article")->insert($adddata);
        return $this->successjson("ok");
    }

    //删除帖子
    public function deletePost()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
            'id|帖子' => 'require|number',
            'usertoken' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("userid和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $postinfo = db("article")->where("id", $data["id"])->find();
        if ($postinfo == null) {
            return $this->errorjson("帖子不存在");
        }
        //查询这个人是否是本版块的版主
        $plateinfo = db("plate")->where("id", $postinfo["plateid"])->where("appid", $data["appid"])->find();
        if ($plateinfo == null) {
            return $this->errorjson("系统错误");
        }
        $plateadmin = explode(",", $plateinfo["admin"]);
        if (inarraybyId($plateadmin, $userinfo["id"])) {
            db("article")->where("id", $data["id"])->delete();
            return $this->successjson("删除成功");
        }
        if ($postinfo["userid"] != $userinfo["id"]) {
            return $this->errorjson("系统异常");
        }
        db("article")->where("id", $data["id"])->delete();
        return $this->successjson("删除成功");
    }

    //编辑帖子
    public function editpost()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
            'usertoken' => 'require',
            'title|标题' => 'require',
            'content|内容' => 'require',
            'id|帖子id' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("userid和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $postinfo = db("article")->where("id", $data["id"])->find();
        if ($postinfo == null) {
            return $this->errorjson("帖子不存在");
        }
        $expand = input("?expand") ? $data["expand"] : "";
        $network_pictures = input("?network_pictures") ? $data["network_pictures"] : "";
        //查询这个人是否是本版主
        $plateinfo = db("plate")->where("id", $postinfo["plateid"])->where("appid", $data["appid"])->find();
        if ($plateinfo == null) {
            return $this->errorjson("系统错误");
        }
        $plateadmin = explode(",", $plateinfo["admin"]);
        if (!inarraybyId($plateadmin, $userinfo["id"])) {
            if ($postinfo["userid"] != $userinfo["id"]) {
                return $this->errorjson("不能修改他人帖子");
            }
        }
        $pic_url = [];
        $video_url = [];
        $video_cover = [];
        if (!empty($_FILES) && !empty($_FILES["file"])) {
            $upload = new Upload();
            $result = $upload->upload('file', 1);
            $result = json_decode($result, true);
            foreach ($result["data"] as $key => $value) {
                array_push($pic_url, $value["filePath"]);
                array_push($video_url, $value["fullPath"]);
            }
        }
        if (!empty($_FILES) && !empty($_FILES["video_cover"])) {
            $upload = new Upload();
            $result_cover = $upload->upload('video_cover', 1);
            $result_cover = json_decode($result_cover, true);
            foreach ($result_cover["data"] as $key => $value) {
                array_push($video_cover, $value["filePath"]);
            }
        }
        $pic_url = implode(",", $pic_url);
        $video_url = implode(",", $video_url);
        $video_cover = implode(",", $video_cover);
        if ($postinfo["is_type"] == 0) {
            $adddata = [
                "title" => $data["title"],
                "content" => $data["content"],
                "pic_url" => $pic_url,
                "updatetime" => date("Y-m-d H:i:s", time()),
                "ip" => get_real_ip(),
                "network_pictures" => $network_pictures,
                "expand" => $expand,
            ];
        } else {
            $adddata = [
                "title" => $data["title"],
                "content" => $data["content"],
                "video_url" => $video_url,
                "video_cover" => $video_cover,
                "updatetime" => date("Y-m-d H:i:s", time()),
                "ip" => get_real_ip(),
                "video_cover" => $expand,
            ];
        }
        db("article")->where("id", $data["id"])->update($adddata);
        return $this->successjson("修改成功");
    }

    //获取待审核帖子
    public function reviewArticle_list()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
            'usertoken' => 'require',
            'plateid|版块id' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("userid和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $plateinfo = db("plate")->where("id", $data["plateid"])->where("appid", $data["appid"])->find();
        if ($plateinfo == null) {
            return $this->errorjson("系统错误");
        }
        $plateadmin = explode(",", $plateinfo["admin"]);
        if (inarraybyId($plateadmin, $userinfo["id"])) {
            $result = db("article")
                ->alias("a")
                ->join("user u", "u.id=a.userid")
                ->join("plate p", "p.id=a.plateid")
                ->field("a.*,u.username,u.nickname,u.usertx,u.title as usertitle,p.platename")
                ->where("a.plateid", $data["plateid"])
                ->where("a.status", 0)
                ->order("a.createtime", "asc")
                ->limit($this->limit)
                ->page($this->page)
                ->select();
            $postcount = db("article")
                ->alias("a")
                ->join("user u", "u.id=a.userid")
                ->join("plate p", "p.id=a.plateid")
                ->field("a.*,u.username,u.nickname,u.usertx,p.platename")
                ->where("a.plateid", $data["plateid"])
                ->where("a.status", 0)
                ->count();
            $pagecount = ceil($postcount / $this->limit);
            foreach ($result as $key => $value) {
                if ($value["video_cover"] != "") {
                    $result[$key]["video_cover"] = Request::domain() . $value["video_cover"];
                }
                $result[$key]["usertx"] = Request::domain() . $value["usertx"];
                //本地图片
                $pic = explode(",", $value["pic_url"]);
                $pic_url_array = [];
                foreach ($pic as $k => $v) {
                    if ($v == "") continue;
                    array_push($pic_url_array, Request::domain() . $v);
                }
                $pic_url = implode(",", $pic_url_array);
                //网络图片
                $network_pictures_start = explode(",", $value["network_pictures"]);
                $network_pictures_array = [];
                foreach ($network_pictures_start as $k1 => $v1) {
                    if ($v1 == "") continue;
                    array_push($network_pictures_array, $v1);
                }
                $network_pictures = implode(",", $network_pictures_array);
                if ($value["pic_url"] != "") {
                    if ($value["network_pictures"] != "") {
                        $result[$key]["pic_url"] = $pic_url . "," . $network_pictures;
                    } else {
                        $result[$key]["pic_url"] = $pic_url;
                    }
                } else {
                    if ($value["network_pictures"] != "") {
                        $result[$key]["pic_url"] = $network_pictures;
                    } else {
                        $result[$key]["pic_url"] = "";
                    }
                }
                unset($result[$key]["network_pictures"]);
                $result[$key]["view"] = db("view")->where("postid", $value["id"])->where("type", 1)->count();
                $result[$key]["thumbs"] = db("view")->where("postid", $value["id"])->where("type", 2)->count();
                //评论量
                $result[$key]["comment"] = db("comments")->where("postid", $value["id"])->count();
            }
            return $this->successjson($pagecount, $result);
        } else {
            return $this->errorjson("您不是管理员");
        }
    }

    //审核帖子
    public function reviewArticle()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
            'usertoken' => 'require',
            'postid|帖子id' => 'require'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("userid和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $postinfo = db("article")->where("id", $data["postid"])->find();
        if ($postinfo == null) {
            return $this->errorjson("帖子不存在");
        }
        $plateinfo = db("plate")->where("id", $postinfo["plateid"])->where("appid", $data["appid"])->find();
        if ($plateinfo == null) {
            return $this->errorjson("系统错误");
        }
        $plateadmin = explode(",", $plateinfo["admin"]);
        if (inarraybyId($plateadmin, $userinfo["id"])) {
            db("article")->where("id", $data["postid"])->update(["status" => 1]);
            return $this->successjson("审核通过");
        } else {
            return $this->errorjson("你不是管理员，无法审核");
        }
    }

    //发表评论
    public function comment()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
            'usertoken' => 'require',
            'postid|帖子id' => 'require|number',
            'content|评论内容' => 'require',
            'parentid|评论的id' => 'number'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $postinfo = db("article")->where("id", $data["postid"])->find();
        if ($postinfo == null) {
            return $this->errorjson("帖子不存在");
        }
        $addcommentdata = [
            "parentid" => $data["parentid"],
            "postid" => $data["postid"],
            "content" => $data["content"],
            "userid" => $userinfo["id"],
            "appid" => $data["appid"],
            "time" => date("Y-m-d H:i:s", time()),
        ];
        $commentid = db("comments")->insertGetId($addcommentdata);
        $this->addmessage($userinfo["id"], 2, $data["postid"], $commentid);
        $adddata = [
            "updatetime" => date("Y-m-d H:i:s", time()),
        ];
        db("article")->where("id", $data["postid"])->update($adddata);
        return $this->successjson("评论成功");
    }

    //删除评论
    public function deleteComment()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
            'usertoken' => 'require',
            'id|评论id' => 'require|number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $commentinfo = db("comments")->where("id", $data["id"])->find();
        if ($commentinfo == null) {
            return $this->errorjson("评论不存在");
        }
        $postinfo = db("article")->where("id", $commentinfo["postid"])->find();
        if ($postinfo == null) {
            return $this->errorjson("系统错误");
        }
        $plateinfo = db("plate")->where("id", $postinfo["plateid"])->where("appid", $data["appid"])->find();
        if ($plateinfo == null) {
            return $this->errorjson("系统错误");
        }
        //查询这个人是否是本版块的版主
        $plateadmin = explode(",", $plateinfo["admin"]);
        if (inarraybyId($plateadmin, $userinfo["id"])) {
            $twoinfo = db("comments")->where("parentid", $commentinfo["id"])->select();
            $this->getParentdel($twoinfo);
            db("comments")->where("id", $data["id"])->delete();
            return $this->successjson("删除成功");
        }
        if ($userinfo["id"] != $commentinfo["userid"]) {
            return $this->errorjson("不能删除其他人的评论哈");
        }
        //删除他的下级评论 (递归删除)
        $twoinfo = db("comments")->where("parentid", $commentinfo["id"])->select();
        $this->getParentdel($twoinfo);
        db("comments")->where("id", $data["id"])->delete();
        return $this->successjson("删除成功");
    }

    //获取评论
    public function listComment()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
            'postid|帖子id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?postid") && !input("?userid")) {
            return $this->errorjson("userid和postid必须传一个");
        }
        $where = "c.appid = {$data['appid']} ";
        if (input("?username") || input("?userid")) {
            if (input("?username")) {
                $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
            }
            if (input("?userid")) {
                $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
            }
            if ($userinfo == null) {
                return $this->errorjson("用户不存在");
            }
            $where .= " and c.userid = {$userinfo['id']}";
        }
        if (input("?postid")) {
            $postinfo = db("article")->where("id", $data["postid"])->find();
            if ($postinfo == null) {
                return $this->errorjson("帖子不存在");
            }
            $where .= " and c.postid = {$postinfo['id']}";
        }
        $sort = input("?sort") ? $data["sort"] : "time";
        $sortOrder = input("?sortOrder") ? $data["sortOrder"] : 'desc';
        if ($sort != "time" && $sort != "id") {
            return $this->errorjson("sort参数错误");
        }
        if ($sortOrder != "desc" && $sortOrder != "asc") {
            return $this->errorjson("sortOrder参数错误");
        }
        $commentinfo = db('comments')
            ->alias("c")
            ->join("user u", "u.id = c.userid")
            ->join("article a", "a.id = c.postid")
            ->where($where)
            ->field("c.*,u.username,u.nickname,u.usertx,u.title as usertitle,a.title as posttitle")
            ->order("c." . $sort, $sortOrder)
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        $commentcount = db("comments")
            ->alias("c")
            ->join("user u", "u.id = c.userid")
            ->join("article a", "a.id = c.postid")
            ->field("c.*")
            ->where($where)
            ->order("c.id", "desc")
            ->count();
        foreach ($commentinfo as $key => $value) {
            $commentinfo[$key]["usertx"] = Request::domain() . $value["usertx"];
            //假入有上级评论则插入
            //上级评论者用户昵称
            $commentinfo[$key]["parentnickname"] = "";
            //上级评论内容
            $commentinfo[$key]["parentcontent"] = "";
            if ($value["parentid"] != 0) {
                $parentcommentinfo = db("comments")
                    ->alias("c")
                    ->join("user u", "u.id = c.userid")
                    ->join("article a", "a.id = c.postid")
                    ->where("c.id", $value["parentid"])
                    ->field("c.id,c.content,u.nickname")
                    ->find();
                //上级评论者用户昵称
                $commentinfo[$key]["parentnickname"] = $parentcommentinfo["nickname"];
                //上级评论内容
                $commentinfo[$key]["parentcontent"] = $parentcommentinfo["content"];
            }
        }
        $pagecount = ceil($commentcount / $this->limit);
        return $this->successjson($pagecount, $commentinfo);
    }

    //点赞/取消点赞
    public function thumbs()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
            'usertoken' => 'require',
            'id|帖子id' => 'require|number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $postinfo = db("article")->where("id", $data["id"])->find();
        if ($postinfo == null) {
            return $this->errorjson("帖子不存在");
        }
        //先判断是否点赞了 帖子
        $thumbsinfo = db("view")->where("postid", $data["id"])->where("userid", $userinfo["id"])->where("type", 2)->find();
        if ($thumbsinfo == null) {
            //未点赞帖子
            $adddata = [
                "appid" => $data["appid"],
                "time" => date("Y-m-d H:i:s", time()),
                "userid" => $userinfo["id"],
                "postid" => $data["id"],
                "type" => 2
            ];
            db("view")->insert($adddata);
            $this->addmessage($userinfo["id"], 1, $data["id"]);
            return $this->successjson("点赞成功");
        } else {
            db("view")->where("postid", $data["id"])->where("userid", $userinfo["id"])->where("type", 2)->delete();
            return $this->successjson("取消点赞成功");
        }
    }

    //获取用户的点赞记录
    public function getthumbslist()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $result = db("view")
            ->alias("v")
            ->join("article a", "a.id=v.postid")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("a.*,u.username,u.nickname,u.usertx,u.title as usertitle,p.platename")
            ->where("v.type", 2)
            ->where("v.userid", $userinfo["id"])
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        $postcount = db("view")
            ->alias("v")
            ->join("article a", "a.id=v.postid")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("a.*,u.username,u.nickname,u.usertx,u.title as usertitle,p.platename")
            ->where("v.type", 2)
            ->where("v.userid", $userinfo["id"])
            ->limit($this->limit)
            ->page($this->page)
            ->count();
        $pagecount = ceil($postcount / $this->limit);
        foreach ($result as $key => $value) {
            if ($value["video_url"] != "") {
                $result[$key]["video_url"] = Request::domain() . $value["video_url"];
            }
            if ($value["video_cover"] != "") {
                $result[$key]["video_cover"] = Request::domain() . $value["video_cover"];
            }
            $result[$key]["usertx"] = Request::domain() . $value["usertx"];
            $pic = explode(",", $value["pic_url"]);
            $pic_url = [];
            foreach ($pic as $k => $v) {
                array_push($pic_url, Request::domain() . $v);
            }
            $result[$key]["pic_url"] = implode(",", $pic_url);
            $result[$key]["view"] = db("view")->where("postid", $value["id"])->where("type", 1)->count();
            $result[$key]["thumbs"] = db("view")->where("postid", $value["id"])->where("type", 2)->count();
            //评论量
            $result[$key]["comment"] = db("comments")->where("postid", $value["id"])->count();
        }
        return $this->successjson($pagecount, $result);
    }

    //浏览历史
    public function browseHistory()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $result = db("view")
            ->alias("v")
            ->join("article a", "a.id=v.postid")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("distinct a.*,u.username,u.nickname,u.usertx,u.title as usertitle,p.platename")
            ->where("v.type", 1)
            ->where("v.userid", $userinfo["id"])
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        $postcount = db("view")
            ->alias("v")
            ->join("article a", "a.id=v.postid")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("a.*,u.username,u.nickname,u.usertx,u.title as usertitle,p.platename")
            ->where("v.type", 1)
            ->where("v.userid", $userinfo["id"])
            ->limit($this->limit)
            ->page($this->page)
            ->count();
        $pagecount = ceil($postcount / $this->limit);
        foreach ($result as $key => $value) {
            if ($value["video_url"] != "") {
                $result[$key]["video_url"] = Request::domain() . $value["video_url"];
            }
            if ($value["video_cover"] != "") {
                $result[$key]["video_cover"] = Request::domain() . $value["video_cover"];
            }
            $result[$key]["usertx"] = Request::domain() . $value["usertx"];
            $pic = explode(",", $value["pic_url"]);
            $pic_url = [];
            foreach ($pic as $k => $v) {
                array_push($pic_url, Request::domain() . $v);
            }
            $result[$key]["pic_url"] = implode(",", $pic_url);
            $result[$key]["view"] = db("view")->where("postid", $value["id"])->where("type", 1)->count();
            $result[$key]["thumbs"] = db("view")->where("postid", $value["id"])->where("type", 2)->count();
            //评论量
            $result[$key]["comment"] = db("comments")->where("postid", $value["id"])->count();
        }
        return $this->successjson($pagecount, $result);
    }

    //获取笔记列表
    public function Noteslist()
    {
        $data = input();
        $rule = [
            'username|用户名' => 'min:5|max:20|alphaNum',
            'userid|用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $where = "n.appid = {$data['appid']} ";
        if (input("?username") || input("?userid")) {
            if (input("?username")) {
                $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
            }
            if (input("?userid")) {
                $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
            }
            if ($userinfo == null) {
                return $this->errorjson("用户不存在");
            }
            $where .= " and n.user_id = {$userinfo['id']}";
        }
        $notesinfo = db("notes")
            ->alias("n")
            ->join("user u", "u.id=n.user_id")
            ->where($where)
            ->field("n.*,u.username,u.usertx,u.nickname,u.title as usertitle")
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        $notescount = db("notes")
            ->alias("n")
            ->join("user u", "u.id=n.user_id")
            ->where($where)
            ->field("n.*,u.username,u.usertx,u.nickname,u.title as usertitle")
            ->count();
        foreach ($notesinfo as $key => $value) {
            $notesinfo[$key]["usertx"] = Request::domain() . $value["usertx"];
        }
        $pagecount = ceil($notescount / $this->limit);
        return $this->successjson($pagecount, $notesinfo);
    }

    public function addNotes()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'number',
            'username|用户名' => 'min:5|max:20|alphaNum',
            'title|笔记标题' => 'require',
            'content|笔记内容' => 'require',
            'usertoken' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $adddate = [
            "title" => $data["title"],
            "content" => $data["content"],
            "ip" => get_real_ip(),
            "creattime" => date("Y-m-d H:i:s", time()),
            "updatetime" => date("Y-m-d H:i:s", time()),
            "appid" => $data["appid"],
            "user_id" => $userinfo["id"],
        ];
        db("notes")->insert($adddate);
        return $this->successjson("添加成功");
    }

    //获取笔记详情
    public function getNotes()
    {
        $data = input();
        $rule = [
            'id|帖子id' => 'require|number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $notesinfo = db("notes")
            ->alias("n")
            ->join("user u", "u.id=n.user_id")
            ->where("n.id", $data["id"])
            ->where("n.appid", $data["appid"])
            ->field("n.*,u.username,u.usertx,u.nickname,u.title as usertitle")
            ->find();
        if ($notesinfo == null) {
            return $this->errorjson("笔记不存在");
        }
        $notesinfo["usertx"] = Request::domain() . $notesinfo["usertx"];
        $notesinfo["notesurl"] = Request::domain() . "/notes/" . $notesinfo["id"] . ".html";
        return $this->successjson("ok", $notesinfo);
    }

    //修改笔记
    public function editNotes()
    {
        $data = input();
        $rule = [
            'id|笔记id' => 'require|number',
            'userid|用户id' => 'number',
            'username|用户名' => 'min:5|max:20|alphaNum',
            'title|笔记标题' => 'require',
            'content|笔记内容' => 'require',
            'usertoken' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $notesinfo = db("notes")->where("id", $data["id"])->find();
        if ($notesinfo == null) {
            return $this->errorjson("笔记不存在");
        }
        if ($notesinfo["user_id"] != $userinfo["id"]) {
            return $this->errorjson("系统错误");
        }
        $updatedata = [
            "title" => $data["title"],
            "content" => $data["content"],
            "ip" => get_real_ip(),
            "updatetime" => date("Y-m-d H:i:s", time()),
        ];
        db("notes")->where("id", $data["id"])->update($updatedata);
        return $this->successjson("修改成功");
    }

    //删除笔记
    public function deletenotes()
    {
        $data = input();
        $rule = [
            'id|笔记id' => 'require|number',
            'userid|用户id' => 'number',
            'username|用户名' => 'min:5|max:20|alphaNum',
            'usertoken' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $notesinfo = db("notes")->where("id", $data["id"])->find();
        if ($notesinfo == null) {
            return $this->errorjson("笔记不存在");
        }
        if ($notesinfo["user_id"] != $userinfo["id"]) {
            return $this->errorjson("系统错误");
        }
        db("notes")->where("id", $data["id"])->delete();
        return $this->successjson("删除成功");
    }

    //获取通知消息
    public function getmessagelist()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'number',
            'username|用户名' => 'min:5|max:20|alphaNum',
            'type|消息类型' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $where = "m.appid = {$data['appid']} and u.user_id = {$userinfo['id']}";
        if (input("?type")) {
            $where .= " and type = {$data['type']}";
        }
        //先查后台发的  先插入数据到mr_message_user表
        $ggmsg = db("message")->where("type", 0)->where("time", ">", $userinfo["create_time"])->select();
        foreach ($ggmsg as $key => $value) {
            $rs = db("message_user")->where('msg_id', $value["id"])->where("user_id", $userinfo["id"])->find();
            if ($rs == null) {
                db("message_user")->insert([
                    "msg_id" => $value["id"],
                    "user_id" => $userinfo["id"],
                    "appid" => $data["appid"]
                ]);
            }
        }
        $messageinfo = db("message")
            ->alias("m")
            ->join("message_user u", "u.msg_id=m.id")
            ->where($where)
            ->field("m.*,u.user_id,u.state")
            ->limit($this->limit)
            ->page($this->page)
            ->order('time', 'desc')
            ->select();
        //未读数量
        $where .= " and u.state = 0";
        $messagecount = db("message")
            ->alias("m")
            ->join("message_user u", "u.msg_id=m.id")
            ->where($where)
            ->field("m.*,u.user_id")
            ->count();
        return $this->successjson($messagecount, $messageinfo);
    }

    //修改消息的未读状态
    public function Updatemsgstate()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'number',
            'username|用户名' => 'min:5|max:20|alphaNum',
            'type|消息类型' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $where = "m.appid = {$data['appid']} and u.user_id = {$userinfo['id']}";
        if (input("?type")) {
            $where .= " and type = {$data['type']}";
        }
        $messageinfo = db("message")
            ->alias("m")
            ->join("message_user u", "u.msg_id=m.id")
            ->where($where)
            ->field("m.*,u.user_id")
            ->limit($this->limit)
            ->page($this->page)
            ->order('time', 'desc')
            ->select();
        foreach ($messageinfo as $key => $value) {
            db("message_user")->where("msg_id", $value["id"])->where("user_id", $value["user_id"])->update(["state" => 1]);
        }
        return $this->successjson("ok");
    }

    //管理员密钥操作
    //增减会员
    public function addMembers()
    {
        $data = input();
        $data["number"] = substr($data["time"], 1);
        $rule = [
            'userid|用户id' => 'number',
            'username|用户名' => 'min:5|max:20|alphaNum',
            'key|key' => 'require',
            'time|时间' => 'require',
            'number|符号后面' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $keyinfo = db("admin")->where("adminkey", $data["key"])->find();
        if ($keyinfo == null) {
            return $this->errorjson("密钥不存在");
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["viptime"] >= time()) {
            $userviptime = $userinfo["viptime"];
        } else {
            $userviptime = time();
        }
        if (strpos($data["time"], '+') === false && strpos($data["time"], '-') === false) {
            return $this->errorjson("必须带有+-符号");
        }
        if (strpos($data["time"], '+') !== false) {
            $viptime = $userviptime + substr($data["time"], 1);
            db("user")->where("id", $userinfo["id"])->update(["viptime" => $viptime]);
        } else {
            $viptime = $userviptime - substr($data["time"], 1);
            db("user")->where("id", $userinfo["id"])->update(["viptime" => $viptime]);
        }
        $logdata = [
            "admin_id" => $userinfo["id"],
            "admin_name" => $userinfo["username"],
            "url" => Request::url(),
            "method" => Request::method(),
            "content" => json_encode($data),
            "ip" => Request::server('REMOTE_ADDR'),
            "useragent" => Request::header()["user-agent"],
            "create_time" => time(),
        ];
        db('system_log')->insert($logdata);
        return $this->successjson("成功");
    }

    //增减金币
    public function addmoney()
    {
        $data = input();
        $data["money"] = substr($data["number"], 1);
        $rule = [
            'userid|用户id' => 'number',
            'username|用户名' => 'min:5|max:20|alphaNum',
            'key|key' => 'require',
            'number|加减个数' => 'require',
            'money|符号后面' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $keyinfo = db("admin")->where("adminkey", $data["key"])->find();
        if ($keyinfo == null) {
            return $this->errorjson("密钥不存在");
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if (strpos($data["number"], '+') === false && strpos($data["number"], '-') === false) {
            return $this->errorjson("必须带有+-符号");
        }
        if (strpos($data["number"], '+') !== false) {
            $money = $userinfo["money"] + substr($data["number"], 1);
            db("user")->where("id", $userinfo["id"])->update(["money" => $money]);
        } else {
            $money = $userinfo["money"] - substr($data["number"], 1);
            if ($money < 0) {
                $money = 0;
            }
            db("user")->where("id", $userinfo["id"])->update(["money" => $money]);
        }
        $logdata = [
            "admin_id" => $userinfo["id"],
            "admin_name" => $userinfo["username"],
            "url" => Request::url(),
            "method" => Request::method(),
            "content" => json_encode($data),
            "ip" => Request::server('REMOTE_ADDR'),
            "useragent" => Request::header()["user-agent"],
            "create_time" => time(),
        ];
        db('system_log')->insert($logdata);
        return $this->successjson("成功");
    }

    //关注用户
    public function followUsers()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'require|number',
            'followedid|关注的用户ID' => 'require|number',
            'usertoken' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        $followeduserinfo = db("user")->where("appid", $data["appid"])->where("id", $data["followedid"])->find();
        if ($userinfo == null || $followeduserinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        if ($data["userid"] == $data["followedid"]) {
            return $this->errorjson("不能关注自己");
        }
        $followinfo = db("follow")->where("userid", $data["userid"])->where("followedid", $data["followedid"])->find();
        if ($followinfo != null) {
            db("follow")->where("id", $followinfo["id"])->delete();
            return $this->successjson("取消关注成功");
        }
        $adddata = [
            "userid" => $data["userid"],
            "followedid" => $data["followedid"],
            "appid" => $data["appid"],
            "create_time" => date("Y-m-d H:i:s", time()),
        ];
        db("follow")->insert($adddata);
        return $this->successjson("关注成功");
    }

    //查询关注状态
    public function followState()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'require|number',
            'loginid|当前登录的用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if (input("?loginid")) {
            $loginuserinfo = db("user")->where("appid", $data["appid"])->where("id", $data["loginid"])->find();
            if ($loginuserinfo == null) {
                return $this->errorjson("用户不存在");
            }
            $followinfo = db("follow")->where("userid", $data["userid"])->where("followedid", $data["loginid"])->find();
            $ffollowinfo = db("follow")->where("userid", $data["loginid"])->where("followedid", $data["userid"])->find();
            if ($followinfo != null) {
                if ($ffollowinfo != null) {
                    $state = 0;   //互相关注
                } else {
                    $state = 1;  //他关注了我
                }
            } else {
                if ($ffollowinfo != null) {
                    $state = 2;   //我关注了他
                } else {
                    $state = 3;  //互相都没有关注
                }
            }
        } else {
            $state = 3;
        }
        return $this->successjson($state);
    }

    //获取用户关注列表
    public function userFollowList()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'require|number',
            'loginid|当前登录的用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $followinfo = db("follow")
            ->alias("f")
            ->join("user u", "u.id=f.followedid")
            ->where("f.appid", $data["appid"])
            ->where("f.userid", $data["userid"])
            ->field("u.id,f.userid,f.followedid,u.username,u.nickname,u.usertx,u.sex,u.signature")
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        if (input("?loginid")) {
            $loginuserinfo = db("user")->where("appid", $data["appid"])->where("id", $data["loginid"])->find();
            if ($loginuserinfo == null) {
                return $this->errorjson("用户不存在");
            }
            foreach ($followinfo as $key => $value) {
                $followinfo[$key]["usertx"] = Request::domain() . $value["usertx"];
                $followinfo[$key]["sex"] = $value["sex"] == 0 ? "男" : "女";
                $ffollowinfo = db("follow")->where("userid", $value["followedid"])->where("followedid", $data["loginid"])->find();
                if ($ffollowinfo != null) {
                    $fffollowinfo = db("follow")->where("userid", $data["loginid"])->where("followedid", $value["followedid"])->find();
                    if ($fffollowinfo != null) {
                        $followinfo[$key]["state"] = 0;   //互相关注
                    } else {
                        $followinfo[$key]["state"] = 1;  //他关注了我
                    }
                } else {
                    $fffollowinfo = db("follow")->where("userid", $data["loginid"])->where("followedid", $value["followedid"])->find();
                    if ($fffollowinfo != null) {
                        $followinfo[$key]["state"] = 2;   //我关注了他
                    } else {
                        $followinfo[$key]["state"] = 3;  //互相都没有关注
                    }
                }
            }
        } else {
            foreach ($followinfo as $key => $value) {
                $followinfo[$key]["usertx"] = Request::domain() . $value["usertx"];
                $followinfo[$key]["sex"] = $value["sex"] == 0 ? "男" : "女";
                $followinfo[$key]["state"] = 3;
            }
        }
        return $this->successjson("ok", $followinfo);
    }

    //用户粉丝列表
    public function userFanList()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'require|number',
            'loginid|当前登录的用户id' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $followinfo = db("follow")
            ->alias("f")
            ->join("user u", "u.id=f.userid")
            ->where("f.appid", $data["appid"])
            ->where("f.followedid", $data["userid"])
            ->field("u.id,f.userid,f.followedid,u.username,u.nickname,u.usertx,u.sex,u.signature")
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        if (input("?loginid")) {
            $loginuserinfo = db("user")->where("appid", $data["appid"])->where("id", $data["loginid"])->find();
            if ($loginuserinfo == null) {
                return $this->errorjson("用户不存在");
            }
            foreach ($followinfo as $key => $value) {
                $followinfo[$key]["usertx"] = Request::domain() . $value["usertx"];
                $followinfo[$key]["sex"] = $value["sex"] == 0 ? "男" : "女";
                $ffollowinfo = db("follow")->where("userid", $value["userid"])->where("followedid", $data["loginid"])->find();
                if ($ffollowinfo != null) {
                    $fffollowinfo = db("follow")->where("userid", $data["loginid"])->where("followedid", $value["userid"])->find();
                    if ($fffollowinfo != null) {
                        $followinfo[$key]["state"] = 0;   //互相关注
                    } else {
                        $followinfo[$key]["state"] = 1;  //他关注了我
                    }
                } else {
                    $fffollowinfo = db("follow")->where("userid", $data["loginid"])->where("followedid", $value["userid"])->find();
                    if ($fffollowinfo != null) {
                        $followinfo[$key]["state"] = 2;   //我关注了他
                    } else {
                        $followinfo[$key]["state"] = 3;  //互相都没有关注
                    }
                }
            }
        } else {
            foreach ($followinfo as $key => $value) {
                $followinfo[$key]["usertx"] = Request::domain() . $value["usertx"];
                $followinfo[$key]["sex"] = $value["sex"] == 0 ? "男" : "女";
                $followinfo[$key]["state"] = 3;
            }
        }
        return $this->successjson("ok", $followinfo);
    }

    //获取我的关注的帖子
    public function followpostlist()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'require|number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $followinfo = db("follow")
            ->alias("f")
            ->join("user u", "u.id=f.followedid")
            ->where("f.appid", $data["appid"])
            ->where("f.userid", $data["userid"])
            ->field("f.userid,f.followedid,u.username,u.nickname,u.usertx")
            ->select();
        $followuserid = [];
        foreach ($followinfo as $key => $value) {
            array_push($followuserid, $value["followedid"]);
        }
        $result = db("article")
            ->alias("a")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("a.*,u.username,u.nickname,u.usertx,u.title as usertitle,p.platename")
            ->where([
                "a.appid" => $data["appid"],
                "a.userid" => $followuserid,
            ])
            ->order("updatetime", "desc")
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        $postcount = db("article")
            ->alias("a")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("a.*,u.username,u.nickname,u.usertx,p.platename")
            ->where([
                "a.appid" => $data["appid"],
                "a.userid" => $followuserid,
            ])
            ->count();
        $pagecount = ceil($postcount / $this->limit);
        foreach ($result as $key => $value) {
            if ($value["video_url"] != "") {
                $result[$key]["video_url"] = Request::domain() . $value["video_url"];
            }
            if ($value["video_cover"] != "") {
                $result[$key]["video_cover"] = Request::domain() . $value["video_cover"];
            }
            $result[$key]["usertx"] = Request::domain() . $value["usertx"];
            $pic = explode(",", $value["pic_url"]);
            $pic_url = [];
            foreach ($pic as $k => $v) {
                array_push($pic_url, Request::domain() . $v);
            }
            $result[$key]["pic_url"] = implode(",", $pic_url);
            $result[$key]["view"] = db("view")->where("postid", $value["id"])->where("type", 1)->count();
            $result[$key]["thumbs"] = db("view")->where("postid", $value["id"])->where("type", 2)->count();
            //评论量
            $result[$key]["comment"] = db("comments")->where("postid", $value["id"])->count();
        }
        return $this->successjson($pagecount, $result);
    }

    //邮件发送接口
    public function sendmail()
    {
        $data = input();
        $rule = [
            'receiver|接收人邮箱' => 'require|email',
            'subject|邮件主题' => 'require',
            'content|邮件内容' => 'require',
            'setfrom|发件人名称' => 'require',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $result = Mail::sendEmail($data["setfrom"], $data["receiver"], $data["subject"], $data["content"], 2);
        if ($result == 1) {
            return $this->successjson("ok");
        } else {
            return $this->errorjson($result);
        }
    }

    //管理员密钥生成卡密
    public function addkm()
    {
        $data = input();
        $rule = [
            'key|key' => 'require',
            'type|卡密类型' => 'require',
            'number|卡密数量' => 'number',
            'length|卡密长度' => 'number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        $keyinfo = db("admin")->where("adminkey", $data["key"])->find();
        if ($keyinfo == null) {
            return $this->errorjson("密钥不存在");
        }
        $returnkm = [];
        if ($data["type"] == 0) {
            $rule = [
                'exp|经验值' => 'require|number',
                'money|金币' => 'require|number',
                'viptime|会员天数' => 'require|number',
            ];
            $validate = new Validate($rule);
            $result = $validate->check($data);
            if (!$result) {
                return $this->errorjson($validate->getError());
            }
            $adddata = [
                "exp" => $data["exp"],
                "money" => $data["money"],
                "viptime" => $data["viptime"],
                "appid" => $data["appid"],
                "classification" => "",
            ];
            for ($i = 0; $i < $data["number"]; $i++) {
                $km = getRandChar($data['length']);
                array_push($returnkm, $km);
                $rs = Db::name("km")->where("appid", $data["appid"])->where("km", $km)->where("type", 1)->find();
                if ($rs == null) {
                    $resdata[$i] = $adddata;
                    $resdata[$i]["km"] = $km;
                    $resdata[$i]["creattime"] = date("Y-m-d H:i:s", time());
                }
            }
            Db::name("km")->insertAll($resdata);
        } else {
            $rule = [
                'expire_time|过期时间' => 'require|number',
            ];
            $validate = new Validate($rule);
            $result = $validate->check($data);
            if (!$result) {
                return $this->errorjson($validate->getError());
            }
            $adddata = [
                "expire" => $data["expire_time"],
                "appid" => $data["appid"],
                "type" => 1,
                "classification" => "",
            ];
            $resdata = [];
            for ($i = 0; $i < $data["number"]; $i++) {
                $km = getRandChar($data['length']);
                array_push($returnkm, $km);
                $rs = Db::name("km")->where("appid", $data["appid"])->where("km", $km)->where("type", 1)->find();
                if ($rs == null) {
                    $resdata[$i] = $adddata;
                    $resdata[$i]["km"] = $km;
                    $resdata[$i]["creattime"] = date("Y-m-d H:i:s", time());
                }
            }
            Db::name("km")->insertAll($resdata);
        }
        $logdata = [
            "admin_id" => 0,
            "admin_name" => '暂无用户名',
            "url" => Request::url(),
            "method" => Request::method(),
            "content" => json_encode($data),
            "ip" => Request::server('REMOTE_ADDR'),
            "useragent" => Request::header()["user-agent"],
            "create_time" => time(),
        ];
        db('system_log')->insert($logdata);
        return $this->successjson("成功", $returnkm);
    }

    //拓展功能
    public function expand_list()
    {
        $data = input("");
        $where = " appid = {$data['appid']}";
        if (@$data["userid"] != "") {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
            if ($userinfo == null) {
                return $this->errorjson("用户不存在");
            }
            $where .= " and userid = {$data['userid']}";
        }
        if (@$data["satus"] != "") {
            $where .= " and satus = {$data['satus']}";
        }
        if (@$data["title"] != "") {
            $where .= " and title like '%" . $data['title'] . "%'";
        }
        $res = Db::name("expand")
            ->where($where)
            ->limit($this->limit)
            ->page($this->page)
            ->select();
        $count = db("expand")
            ->where($where)
            ->count();
        $pagecount = ceil($count / $this->limit);
        return $this->successjson($pagecount, $res);
    }

    public function expand_add()
    {
        $data = input("");
        $adddata = [];
        $adddata["appid"] = $data["appid"];
        if ($data["userid"] != "") {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
            if ($userinfo == null) {
                return $this->errorjson("用户不存在");
            }
            $adddata["userid"] = $data["userid"];
        }
        if ($data["satus"] != "") {
            $adddata["satus"] = $data["satus"];
        }
        if ($data["title"] != "") {
            $adddata["title"] = $data["title"];
        }
        if ($data["content"] != "") {
            $adddata["content"] = $data["content"];
        }
        if ($data["icon"] != "") {
            $adddata["icon"] = $data["icon"];
        }
        $adddata["creattime"] = date("Y-m-d H:i:s", time());
        Db::name("expand")->allowEmpty(true)->insert($adddata);
        return $this->successjson("ok");
    }

    //未读消息条数
    public function getunreadMessage()
    {
        $data = input();
        $rule = [
            'userid|用户id' => 'number',
            'username|用户名' => 'min:5|max:20|alphaNum',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        $ggmsg = db("message")->where("type", 0)->where("time", ">", $userinfo["create_time"])->select();
        foreach ($ggmsg as $key => $value) {
            $rs = db("message_user")->where('msg_id', $value["id"])->where("user_id", $userinfo["id"])->find();
            if ($rs == null) {
                db("message_user")->insert([
                    "msg_id" => $value["id"],
                    "user_id" => $userinfo["id"],
                    "appid" => $data["appid"]
                ]);
            }
        }
        $res = [];
        for ($i = 0; $i < 6; $i++) {
            $where = "m.appid = {$data['appid']} and u.user_id = {$userinfo['id']} and u.state = 0";
            $where .= " and m.type = {$i}";
            $messagecount = db("message")
                ->alias("m")
                ->join("message_user u", "u.msg_id=m.id")
                ->where($where)
                ->field("m.*,u.user_id")
                ->count();
            if ($i == 0) {
                $res["syscount"] = $messagecount;
                continue;
            }
            if ($i == 1) {
                $res["likecount"] = $messagecount;
                continue;
            }
            if ($i == 2) {
                $res["commentcount"] = $messagecount;
                continue;
            }
            if ($i == 3) {
                $res["signcount"] = $messagecount;
                continue;
            }
            if ($i == 4) {
                $res["bycount"] = $messagecount;
                continue;
            }
            if ($i == 5) {
                $res["kmcount"] = $messagecount;
                continue;
            }
        }
        return $this->successjson("ok", $res);
    }

    //置顶/热门/帖子状态修改
    public function post_status()
    {
        $data = input();
        $rule = [
            'id|帖子id' => 'require|number',
            'type|修改类型' => 'require|number',
            'typevalue|状态' => 'require|number',
        ];
        $validate = new Validate($rule);
        $result = $validate->check($data);
        if (!$result) {
            return $this->errorjson($validate->getError());
        }
        if (!input("?username") && !input("?userid")) {
            return $this->errorjson("id和用户名必须传一个");
        }
        if ($data["typevalue"] != 0 && $data["typevalue"] != 1) {
            return $this->errorjson("typevalue值错误");
        }
        if (input("?username")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("username", $data["username"])->find();
        }
        if (input("?userid")) {
            $userinfo = db("user")->where("appid", $data["appid"])->where("id", $data["userid"])->find();
        }
        if ($userinfo == null) {
            return $this->errorjson("用户不存在");
        }
        if ($userinfo["usertoken"] != $data["usertoken"]) {
            return $this->errorjson("usertoken错误");
        }
        $postinfo = db("article")
            ->alias("a")
            ->join("user u", "u.id=a.userid")
            ->join("plate p", "p.id=a.plateid")
            ->field("a.*,u.username,u.nickname,u.usertx,u.title as usertitle,p.platename")
            ->where("a.id", $data["id"])
            ->find();
        if ($postinfo == null) {
            return $this->errorjson("帖子不存在");
        }
        $plateinfo = db("plate")->where("id", $postinfo["plateid"])->where("appid", $data["appid"])->find();
        if ($plateinfo == null) {
            return $this->errorjson("系统错误");
        }
        $plateadmin = explode(",", $plateinfo["admin"]);
        if (inarraybyId($plateadmin, $userinfo["id"])) {
            //置顶
            if ($data["type"] == 0) {
                $adddata = [
                    "top" => $data["typevalue"],
                ];
                db("article")->where("id", $data["id"])->update($adddata);
                return $this->successjson("成功");
            }
            if ($data["type"] == 1) {
                $adddata = [
                    "popular" => $data["typevalue"],
                ];
                db("article")->where("id", $data["id"])->update($adddata);
                return $this->successjson("成功");
            }
            if ($data["type"] == 2) {
                if ($data["typevalue"] == 0) {
                    $data["typevalue"] = 1;
                } else {
                    $data["typevalue"] = 3;
                }
                $adddata = [
                    "status" => $data["typevalue"],
                ];
                db("article")->where("id", $data["id"])->update($adddata);
                return $this->successjson("成功");
            }
        } else {
            return $this->errorjson("权限不够");
        }
    }
}
